const pool = require('../../config/db.config');

async function saveNews(news) {
  const connection = await pool.getConnection();
  
  try {
    await connection.beginTransaction();
    
    // 插入新闻主记录
    const [newsResult] = await connection.execute(
      `INSERT INTO news 
       (title, summary, url, pub_date, source, created_at)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [news.title, news.summary, news.url, news.pubDate, news.source, news.createdAt]
    );
    
    const newsId = newsResult.insertId;
    
    // 如果有图片，插入图片记录
    if (news.imageUrl && news.imagePath) {
      await connection.execute(
        `INSERT INTO news_images 
         (news_id, original_url, local_path)
         VALUES (?, ?, ?)`,
        [newsId, news.imageUrl, news.imagePath]
      );
    }
    
    // 如果解析了文章内容，更新新闻记录
    if (news.content) {
      await connection.execute(
        `UPDATE news 
         SET content = ?, author = ?
         WHERE id = ?`,
        [news.content, news.author, newsId]
      );
    }
    
    await connection.commit();
    return newsId;
  } catch (error) {
    await connection.rollback();
    console.error('保存新闻失败', error);
    throw error;
  } finally {
    connection.release();
  }
}

async function checkUrlExists(url) {
  const [rows] = await pool.execute(
    'SELECT id FROM news WHERE url = ?',
    [url]
  );
  
  return rows.length > 0;
}

module.exports = {
  saveNews,
  checkUrlExists
};  